package com.nus.iss.ad.dbhelper;

import org.json.JSONObject;

import com.nus.iss.ad.model.LoginModel;
import com.nus.iss.ad.model.LoginUserInfo;
import com.nus.iss.ad.utils.JsonParser;
import com.nus.iss.ad.utils.MyConfig;
import com.google.gson.Gson;

public class AuthenticateDBHelper {

	public void logout(){
		 String url=MyConfig.BACKEND_PATH + "/api/logout"  ;
		 JsonParser.getJSONFromUrl(url);
		 LoginUserInfo.currentUser=null;
	}
	
	public boolean login(LoginModel loginModel){
		boolean result=false;
		Gson g=new Gson();
		String jsonLoginModel=g.toJson(loginModel);
		//String jsonLoginModel=g.toJson(new LoginModel("admin","admin"));
		
		String url=MyConfig.BACKEND_PATH + "/api/login";
		String[] outJsonResult=new String[1];
		result=JsonParser.authenticatePost(url,jsonLoginModel,outJsonResult); 
		/*
		{"isDelegate":true,
		"deptDelegate":true,
		"username":"emp1",
		"deptId":"2",
		"deptName":"Science Department",
		"name":"Employee One",
		"role":"employeeHead"}
		*/
		
		LoginUserInfo loginUser=null;
		if(result){
			
			//No nested object. So use Gson to convert jsonstring result to LoginUserInfo directly
			Gson gson=new Gson();
			loginUser=gson.fromJson(outJsonResult[0], LoginUserInfo.class);
			
		}else{
			loginUser=null;
		}
		LoginUserInfo.currentUser=loginUser;
		
		return result;
	}
}
